package com.bootdo.sz.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.common.domain.DictDO;
import com.bootdo.common.service.DictService;
import com.bootdo.common.utils.Constants;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.ExportExcel;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.config.ShiroConfig;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;
import com.bootdo.sz.domain.BDSumDO;
import com.bootdo.sz.domain.BdDO;
import com.bootdo.sz.service.BdService;

/**
 * 索致网络科技-保单表
 * 
 * @author zhuzi
 * @email zhuzhaoyong1991@163.com
 * @date 2019-09-06 17:27:36
 */
 
@Controller
@RequestMapping("/sz/bd")
public class BdController {
	@Autowired
	private BdService bdService;
	@Autowired
	private DictService dictService;
//	@Autowired
//	private SeqService seqService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserDao userMapper;
	
	@GetMapping()
	@RequiresPermissions("sz:bd:bd")
	String Bd(){
	    return "sz/bd/bd";
	}
	
	@ResponseBody
	@GetMapping("/getAddBDCount")
	R getAddBDCount(Long userId){
		if(userId == null) {
			userId = ShiroUtils.getUserId();
		}
		List<Long> userRole = userService.getUserRole(userId);
        Long roleId = userRole.get(0);
        Integer bdQuan = 0;
        if(roleId == 60 || roleId == 62) {
        	UserDO userDO = userService.get(userId);
        	if(userDO.getBelongProxy() == null) {
        		// 一级管理员先跳过
        		return R.ok();
        	}
        	UserDO userDO2 = userService.get(Long.valueOf(userDO.getBelongProxy()));
        	bdQuan = userDO2.getBdQua();
        } else if(roleId == 61) {
        	UserDO userDO = userService.get(userId);
        	bdQuan = userDO.getBdQua();
        }
		return (bdQuan != null && bdQuan > 0) ? R.ok() : R.error("保单数量已达到上限，请与服务商联系");
	}
	
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("sz:bd:bd")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
        // 权限处理 4s店只查看自己创建
        // 代理商查看所有拥有的4s店信息
        Long userId = ShiroUtils.getUserId();
        List<Long> userRole = userService.getUserRole(userId);
        Long roleId = userRole.get(0);
        if(roleId == 61) {
        	// 代理商
        	query.put("belongProxy", userId);
        	query.put("roleId", "62");
        	List<UserDO> list4s = userMapper.listAccount(query);
        	List<Long> list4sUserIds = new ArrayList<>();
        	for(UserDO udo : list4s) {
        		list4sUserIds.add(udo.getUserId());
        	}
        	query.put("userIds", list4sUserIds);
        } else if(roleId == 62) {
        	// 4s店
        	query.put("userId", userId);
        }
		List<BdDO> bdList = bdService.list(query);
		int total = bdService.count(query);
		PageUtils pageUtils = new PageUtils(bdList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("sz:bd:add")
	String add(Model model){
//		List<DictDO> bdStatusList = dictService.listByType("bdStatus");
		List<DictDO> bdValidList = dictService.listByType("bdValid");
		List<DictDO> buyTypeList = dictService.listByType("buyType");
//		model.addAttribute("bdStatusList", bdStatusList);
		model.addAttribute("bdValidList", bdValidList);
		model.addAttribute("buyTypeList", buyTypeList);
		Long userId = ShiroUtils.getUserId();
		List<Long> userRole = userService.getUserRole(userId);
		Long roleId = userRole.get(0);
		Map<String, Object> query = null;
		if(roleId == 60) {
			query = new HashMap<String, Object>();
			query.put("roleId", "62");
			List<UserDO> listAccount = userMapper.listAccount(query);
			model.addAttribute("user4ss", listAccount);
		} else if(roleId == 61) {
			query = new HashMap<String, Object>();
			query.put("roleId", "62");
			query.put("belongProxy", userId);
			List<UserDO> listAccount = userMapper.listAccount(query);
			model.addAttribute("user4ss", listAccount);
		} else {
			model.addAttribute("user4ss", null);
		}
	    return "sz/bd/add";
	}
	
	@GetMapping("/printPreview/{id}")
	String printPreview(@PathVariable("id") Long id, Model model){
		BdDO bdDO = bdService.get(id);
		bdDO.setBdValid(Constants.CHINA_DITITAL[Integer.parseInt(bdDO.getBdValid()) - 1]);
		model.addAttribute("bdModel", bdDO);
	    return "sz/bd/print_preview";
	}
	
	@GetMapping("/visitorPrintPreview/{id}")
	String visitorPrintPreview(@PathVariable("id") Long id, Model model){
		BdDO bdDO = bdService.get(id);
		bdDO.setBdValid(Constants.CHINA_DITITAL[Integer.parseInt(bdDO.getBdValid())]);
		model.addAttribute("bdModel", bdDO);
	    return "sz/bd/print_preview";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("sz:bd:edit")
	String edit(@PathVariable("id") Long id,Model model){

//		List<DictDO> bdStatusList = dictService.listByType("bdStatus");
		List<DictDO> bdValidList = dictService.listByType("bdValid");
		List<DictDO> buyTypeList = dictService.listByType("buyType");
//		model.addAttribute("bdStatusList", bdStatusList);
		model.addAttribute("bdValidList", bdValidList);
		model.addAttribute("buyTypeList", buyTypeList);
		BdDO bd = bdService.get(id);
		model.addAttribute("bd", bd);
	    return "sz/bd/edit";
	}
	
	@GetMapping("/see/{id}")
	@RequiresPermissions("sz:bd:see")
	String see(@PathVariable("id") Long id,Model model){

//		List<DictDO> bdStatusList = dictService.listByType("bdStatus");
		List<DictDO> bdValidList = dictService.listByType("bdValid");
		List<DictDO> buyTypeList = dictService.listByType("buyType");
//		model.addAttribute("bdStatusList", bdStatusList);
		model.addAttribute("bdValidList", bdValidList);
		model.addAttribute("buyTypeList", buyTypeList);
		BdDO bd = bdService.get(id);
		model.addAttribute("bd", bd);
	    return "sz/bd/see";
	}
	
	@GetMapping("/getBD")
	String getBD(){
//		BdDO bd = bdService.getBD(productNo, vinCode);
	    return "sz/bd/bd_search";
	}
	
	@ResponseBody
	@GetMapping("/getBDData")
	R getBDData(String productNo, String vinCode){
		BdDO bd = bdService.getBD(productNo, vinCode);
		if(null != bd) {
			Map<String, Object> map = new HashMap<>();
			map.put("bd", bd);
			return R.ok(map);
		}
		return R.error("未查询到您的保单信息");
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("sz:bd:add")
	public R save( BdDO bd){
		if(bdService.saveBd(bd)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("sz:bd:edit")
	public R update( BdDO bd){
		bd.setBdEndDate(DateUtils.getBdEndDate(bd.getBdStartDate(), Integer.valueOf(bd.getBdValid())));
		bd.setUpdateDate(new Date());
		UserDO user = ShiroUtils.getUser();
		bd.setUpdateBy(user.getName());
		bdService.update(bd);
		return R.ok();
	}
	
	@ResponseBody
	@RequestMapping("/updateBDQua")
	@RequiresPermissions("sz:bd:updateBDQua")
	public R updateBDQua(UserDO udo, Integer type){
		if(type == 0) {
			// 重置
			userService.resetBDQua(udo);
		} else {
			userService.editBDQua(udo);
		}
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("sz:bd:remove")
	public R remove( Long id){
		if(bdService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	@PostMapping( "/trash")
	@ResponseBody
	@RequiresPermissions("sz:bd:remove")
	public R trash( Long id){
		BdDO bdDO = bdService.get(id);
		bdDO.setStatus("1");
		if(bdService.update(bdDO)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("sz:bd:batchRemove")
	public R remove(@RequestParam("ids[]") Long[] ids){
		bdService.batchRemove(ids);
		return R.ok();
	}
	
	@GetMapping("/exportBD")
	@RequiresPermissions("sz:bd:exportBD")
	public void exportMonth(String searchType, String searchName, String bdStartDates, String bdStartDatee, String bdCreateDates, String bdCreateDatee, @RequestParam Map<String, Object> params, HttpServletResponse response){
		//查询列表数据
		params.put("searchType", searchType);
		params.put("searchName", searchName);
		params.put("bdStartDates", bdStartDates);
		params.put("bdStartDatee", bdStartDatee);
		params.put("bdCreateDates", bdCreateDates);
		params.put("bdCreateDatee", bdCreateDatee);
		ExportExcel<BdDO> export = new ExportExcel<>();
			try {
			response.setContentType("application/msexcel;charset=utf-8");
			response.setHeader("content-Type", "application/vnd.ms-excel");
			response.setHeader("content-disposition", "attachment;filename=" + new String(("销售单.xls").getBytes("UTF-8"), "ISO8859-1"));
			
			Map<String, String> columnNames = new LinkedHashMap<String, String>();
			columnNames.put("bdOnDate", "安装日期");
			columnNames.put("bdNo", "保单号");
			columnNames.put("status", "保单状态");
			columnNames.put("customerType", "客户类型");
			columnNames.put("carHolderName", "客户姓名");
			columnNames.put("carHolderPhone", "联系电话");
			columnNames.put("idcardType", "证件类型");
			columnNames.put("carHolderIdcard", "身份证号");
			columnNames.put("carHolderAddress", "联系地址");
			columnNames.put("carSupplier", "车辆厂牌");
			columnNames.put("carTypeNo", "车辆型号");
			columnNames.put("vinCode", "VIN码");
			columnNames.put("egineNo", "发动机号");
			columnNames.put("deviceType", "设备型号");
			columnNames.put("productNo", "设备编号");
//			columnNames.put("simNo", "SIM卡号");
			columnNames.put("carRegistrationDate", "登记日期");
			columnNames.put("fs", "4s店");
			columnNames.put("position", "安装地点");
			columnNames.put("bdStartBy", "安装人");
//			columnNames.put("cardNo", "卡号");
			columnNames.put("carPrice", "新车价格");
			columnNames.put("carBelong", "第一受益人");
			columnNames.put("bdValid", "保险期限");
			columnNames.put("bdStartDate", "保险开始时间");
			columnNames.put("bdEndDate", "保险结束时间");
			columnNames.put("createBy", "录入人");
			columnNames.put("createDate", "生效时间");
			columnNames.put("carSaler", "销售顾问");
//			columnNames.put("safeNo", "保险单号");
			
			// 权限处理 4s店只查看自己创建
	        // 代理商查看所有拥有的4s店信息
	        Long userId = ShiroUtils.getUserId();
	        List<Long> userRole = userService.getUserRole(userId);
	        Long roleId = userRole.get(0);
	        if(roleId == 61) {
	        	// 代理商
	        	params.put("belongProxy", userId);
	        	params.put("roleId", "62");
	        	List<UserDO> list4s = userMapper.listAccount(params);
	        	List<Long> list4sUserIds = new ArrayList<>();
	        	for(UserDO udo : list4s) {
	        		list4sUserIds.add(udo.getUserId());
	        	}
	        	params.put("userIds", list4sUserIds);
	        } else if(roleId == 62) {
	        	// 4s店
	        	params.put("userId", userId);
	        }
	        
			List<BdDO> bdDOList = bdService.list(params);
			
			export.exportExcel("销售单", "system", columnNames, bdDOList, response, DateUtils.DATE_TIME_PATTERN);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@GetMapping("/exportBDSum")
	@RequiresPermissions("sz:bd:exportBDSum")
	public void exportBDSum(String searchType, String searchName, String bdStartDates, String bdStartDatee, String bdCreateDates, String bdCreateDatee, @RequestParam Map<String, Object> params, HttpServletResponse response){
		//查询列表数据
		params.put("searchType", searchType);
		params.put("searchName", searchName);
		params.put("bdStartDates", bdStartDates);
		params.put("bdStartDatee", bdStartDatee);
		params.put("bdCreateDates", bdCreateDates);
		params.put("bdCreateDatee", bdCreateDatee);
		ExportExcel<BDSumDO> export = new ExportExcel<>();
			try {
			response.setContentType("application/msexcel;charset=utf-8");
			response.setHeader("content-Type", "application/vnd.ms-excel");
			response.setHeader("content-disposition", "attachment;filename=" + new String(("销售单录入汇总.xls").getBytes("UTF-8"), "ISO8859-1"));
			
			Map<String, String> columnNames = new LinkedHashMap<String, String>();
			columnNames.put("xh", "序号");
			columnNames.put("fs", "授权网点");
			columnNames.put("createBy", "录入人");
			columnNames.put("allTotal", "录入总订单数");
			columnNames.put("normalTotal", "正常单数");
			columnNames.put("trashTotal", "作废单数");
			
			// 权限处理 4s店只查看自己创建
	        // 代理商查看所有拥有的4s店信息
	        Long userId = ShiroUtils.getUserId();
	        List<Long> userRole = userService.getUserRole(userId);
	        Long roleId = userRole.get(0);
	        if(roleId == 61) {
	        	// 代理商
	        	params.put("belongProxy", userId);
	        	params.put("roleId", "62");
	        	List<UserDO> list4s = userMapper.listAccount(params);
	        	List<Long> list4sUserIds = new ArrayList<>();
	        	for(UserDO udo : list4s) {
	        		list4sUserIds.add(udo.getUserId());
	        	}
	        	params.put("userIds", list4sUserIds);
	        } else if(roleId == 62) {
	        	// 4s店
	        	params.put("userId", userId);
	        }
	        
			List<BDSumDO> bdSumDOList = bdService.bdSumList(params);
			
			String dateRange = bdCreateDates + " - " + bdCreateDatee;
			
			BDSumDO bdSumDO = bdService.bdSum(params);
			int allTotal = (bdSumDO == null ? 0 : (bdSumDO.getAllTotal() == null ? 0 : bdSumDO.getAllTotal()));
			int normalTotal = (bdSumDO == null ? 0 : (bdSumDO.getNormalTotal() == null ? 0 : bdSumDO.getNormalTotal()));
			int trashTotal = (bdSumDO == null ? 0 : (bdSumDO.getTrashTotal() == null ? 0 : bdSumDO.getTrashTotal()));
			export.exportBDSum(dateRange, allTotal, normalTotal, trashTotal, "销售单录入汇总", "system", columnNames, bdSumDOList, response, DateUtils.DATE_TIME_PATTERN);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
